﻿using DevExpress.XtraEditors;
using DLL;
using Microsoft.Win32;
using NursingFormSystem.BLL;
using NursingFormSystem.Model;
using SQLDLL;
using System;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;

namespace NursingFormSystem.BloodGlucoseMonitoring
{
    public partial class BloodGlucForm : XtraForm
    {
        #region 变量声明
        public static Tb_User LoginUser;
        public DataTable PName;
        public string[] name_bed;
        public string[] Patientinfo;
        public string PID = string.Empty;
        public string VID = string.Empty;
        public string[] UserParam;
        #endregion

        #region 构造函数
        public BloodGlucForm(string[] UserParam, string[] patientinfo)
        {
            InitLoginUser(UserParam);
            InitializeComponent();
            this.UserParam = UserParam;
            this.Patientinfo = patientinfo;
        }
        public Tb_User InitLoginUser(string[] UserParam)
        {
            LoginUser = new Tb_User();
            LoginUser.UserId = UserParam[0];
            LoginUser.UserName = UserParam[1];
            LoginUser.DepartmentCode = UserParam[2];
            LoginUser.DepartmentName = UserParam[3];
            LoginUser.JobTitle = UserParam[4];
            LoginUser.PositionTitle = UserParam[5];
            return LoginUser;
        }
        #endregion

        #region 窗体加载
        private void BloodGlucForm_Load(object sender, EventArgs e)
        {
            string NameSelect = @"use BNNursingDocsSystem_Develop; SELECT PATIENT_NAME +'    '+ BED_NO  as Name_Bed ,PATIENT_ID,BED_NO,PATIENT_NAME,NURSE_CELL_CODE,NURSE_CELL_NAME,VISIT_ID,SEX,AGE,IN_DATE FROM [V_YDHL_PATIENT](NOLOCK) where  NURSE_CELL_CODE = '{0}' and STATUS='住院' order by BED_NO";
            NameSelect = string.Format(NameSelect, LoginUser.DepartmentCode);
            DataSet NameList = SqlHelper.ExecuteDataset(NameSelect, System.Data.CommandType.Text);
            PName = NameList.Tables[0];
            name_bed = new string[PName.Rows.Count];
            for (int i = 0; i < PName.Rows.Count; i++)
            {
                name_bed[i] = PName.Rows[i][0].ToString();
                cbb_PatientSel.Properties.Items.Add(name_bed[i]);
            }
            cbb_PatientSel.SelectedIndex = 0;
            cbb_PatientSel.EditValue = this.Patientinfo[2] + "    " + this.Patientinfo[5];

            dateE_StartTime.DateTime = DateTime.Now.AddDays(-30);
            dateE_EndTime.DateTime = DateTime.Now;

            for (int i = 0; i < bandedGridView1.Columns.Count; i++)
            {
                bandedGridView1.Columns[i].Width = Convert.ToInt32(bandedGridView1.Columns[i].Width * 1.3);
            }
            cbb_PatientSel_SelectedIndexChanged(null, null);
        }
        #endregion

        #region 新增事件
        /// <summary>
        /// 新增血糖单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Add_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cbb_PatientSel.Text.Trim()))
            {
                XtraMessageBox.Show("请选择需要新增血糖单的患者。");
                return;
            }
            string PID = this.Patientinfo[0];
            string VisitID = this.Patientinfo[1];
            string bedno = this.Patientinfo[5];
            string Name = this.Patientinfo[2];
            BloodGlucEntryForm NEF = new BloodGlucEntryForm(this.UserParam, this.Patientinfo, "-1");
            NEF.ShowDialog();
            cbb_PatientSel_SelectedIndexChanged(null, null);
        }
        #endregion

        #region 查询事件
        /// <summary>
        /// 查询
        /// </summary>
        private void btn_Query_Click(object sender, EventArgs e)
        {
            cbb_PatientSel_SelectedIndexChanged(null, null);
        }
        #endregion

        #region 血糖单打印
        private void btn_PrintView_Click(object sender, EventArgs e)
        {
            if (bandedGridView1.RowCount == 0) { return; }
            Update_GrfInitial();
            int[] ID = new int[bandedGridView1.RowCount];
            for (int i = 0; i < bandedGridView1.RowCount; i++)
            {
                object obj = bandedGridView1.GetDataRow(i)["ID"];
                if (obj == DBNull.Value) continue;
                if (obj == null) continue;
                if (string.IsNullOrEmpty(obj.ToString())) continue;
                if (!Regex.IsMatch(obj.ToString(), @"^\d+$")) continue;
                ID[i] = Convert.ToInt32(obj);
            }
            PatientInfoView PatParams = new PatientInfoView();
            string PID = this.cbb_PatientSel.Text;
            PID = this.Patientinfo[0];
            string VisitID = this.Patientinfo[1];
            string bedno = this.Patientinfo[5];
            string Name = this.Patientinfo[2];
            PatParams.PATIENT_ID = PID;
            PatParams.BED_NO = bedno;
            PatParams.PATIENT_NAME = Name;
            PatParams.NURSE_CELL_NAME = this.Patientinfo[11];
            PatParams.AGE = this.Patientinfo[4];
            if (!string.IsNullOrEmpty(this.Patientinfo[6]))
                PatParams.IN_DATE = Convert.ToDateTime(this.Patientinfo[6]);
            if (!string.IsNullOrEmpty(this.Patientinfo[7]))
                PatParams.IN_DEPARTMENT_DATE = Convert.ToDateTime(this.Patientinfo[7]);
            PatParams.PATIENT_ID = PID;

            //旧的打印方式
            BloodGlucPrint xx = new BloodGlucPrint(ID, PatParams);
            //新的打印方式
            //BloodGlucPrints xx = new BloodGlucPrints(ID, PatParams);
            xx.ShowDialog();
        }

        //设置报表初始
        private void Update_GrfInitial()
        {
            if (bandedGridView1.RowCount == 0)
            {
                XtraMessageBox.Show("没有要打印的条目哦");
                return;
            }
            string[] ID = new string[bandedGridView1.RowCount];
            for (int i = 0; i < bandedGridView1.RowCount; i++)
            {
                ID[i] = bandedGridView1.GetDataRow(i)["ID"].ToString();
                ReportFetchRecord(ID[i]);
            }
        }

        /// <summary>
        /// 赋值
        /// </summary>
        private void ReportFetchRecord(string id)
        {
            string temp = string.Format(@"SELECT *  FROM [BNNursingDocsSystem_Develop].[dbo].[t_Bloodsugar_Print](NOLOCK) where BloodsugarId ='{0}'", id);
            DataTable tempNursingForm = SqlHelper.ExecuteDataset(temp, System.Data.CommandType.Text).Tables[0];
            if (tempNursingForm == null || tempNursingForm.Rows.Count == 0)  //无记录
            {
                InsertClinicalNursingPrint(id);
            }
            else
            {
                UpdateClinicalNursingPrint(id);//有记录
            }

        }
        private void InsertClinicalNursingPrint(string id)
        {
            string PID = this.Patientinfo[0];
            //DataRow CurRow = PName.Select("Name_Bed like '" + PID.Trim() + "%'")[0];
            //PID = CurRow["PATIENT_ID"].ToString();
            string VisitID = this.Patientinfo[1];
            string Bed_No = this.Patientinfo[5];
            string InDate = this.Patientinfo[6];
            string PatientName = this.Patientinfo[2];
            string Age = this.Patientinfo[4];
            string selectsql = @"SELECT[Id],[PatientId],[VISIT_ID],[PatientName],[DepId],[DepName],[AreaId],[AreaName],[Date],[Time],[data],[SubmituserId],[SubmituserName],[Updatetime],[UpdateuserId],[UpdateuserName],[syncSN] FROM [BNNursingDocsSystem_Develop].[dbo].[t_Bloodsugar](NOLOCK) where Id='{0}'";
            selectsql = string.Format(selectsql, id);
            DataTable selectNursingForm = SqlHelper.ExecuteDataset(selectsql, System.Data.CommandType.Text).Tables[0];
            if (selectNursingForm == null || selectNursingForm.Rows.Count <= 0) return;
            XmlDocument xmlDoc = new XmlDocument();
            StringReader Nurseingdata = new StringReader(selectNursingForm.Rows[0]["data"].ToString());
            xmlDoc.Load(Nurseingdata);
            XmlNode nursingrecord = xmlDoc.SelectSingleNode("/BloodSugarRecordDocument");
            string WeeHour = nursingrecord.ChildNodes[0].InnerText.Trim();
            string breadfastbefore = nursingrecord.ChildNodes[1].InnerText.Trim();
            string breadfastafter = nursingrecord.ChildNodes[2].InnerText.Trim();
            string lunchbefore = nursingrecord.ChildNodes[3].InnerText.Trim();
            string lunchafter = nursingrecord.ChildNodes[4].InnerText.Trim();
            string dinnerbefore = nursingrecord.ChildNodes[5].InnerText.Trim();
            string dinnerafter = nursingrecord.ChildNodes[6].InnerText.Trim();
            string bedtime = nursingrecord.ChildNodes[7].InnerText.Trim();
            string sugar1 = nursingrecord.ChildNodes[8].InnerText.Trim();
            string sugartime1 = nursingrecord.ChildNodes[9].InnerText.Trim();
            string sugar2 = nursingrecord.ChildNodes[10].InnerText.Trim();
            string sugartime2 = nursingrecord.ChildNodes[11].InnerText.Trim();
            string sugar3 = nursingrecord.ChildNodes[12].InnerText.Trim();
            string sugartime3 = nursingrecord.ChildNodes[13].InnerText.Trim();
            string sugar4 = nursingrecord.ChildNodes[14].InnerText;
            string sugartime4 = nursingrecord.ChildNodes[15].InnerText;
            string ketone1 = nursingrecord.ChildNodes[16].InnerText;
            string ketonetime1 = nursingrecord.ChildNodes[17].InnerText;
            string ketone2 = nursingrecord.ChildNodes[18].InnerText;
            string ketonetime2 = nursingrecord.ChildNodes[19].InnerText;
            string date = selectNursingForm.Rows[0]["Date"].ToString();
            string time = selectNursingForm.Rows[0]["Time"].ToString();
            string DepId = selectNursingForm.Rows[0]["DepId"].ToString();
            string DepName = selectNursingForm.Rows[0]["DepName"].ToString();
            string syncSN = selectNursingForm.Rows[0]["syncSN"].ToString();

            string TempInsert = @"use BNNursingDocsSystem_Develop ;insert into dbo.t_Bloodsugar_Print
                                         ([BloodsugarId]     ,[PatientId],[VISIT_ID],[PatientName]  ,[Age]       ,[Bed_No]      ,[InTime]   ,[DepId]      ,[DepName]    ,AreaId, AreaName  ,[Date]      ,[Time]      ,[WeeHour]      ,[breadfastbefore]      ,[breadfastafter]      ,[lunchbefore]      ,[lunchafter]      ,[dinnerbefore]      ,[dinnerafter]      ,[bedtime]      ,[sugar1]      ,[sugartime1]      ,[sugar2]      ,[sugartime2]      ,[sugar3]      ,[sugartime3]      ,[sugar4]    ,[sugartime4],[ketone1] ,[ketonetime1] ,[ketone2] ,[ketonetime2] ,[SubmituserId]      ,[SubmituserName]      ,[PrintTime],[syncSN])
                                         VALUES(
                                         '" + id + @"','" + PID + @"'," +
                                      " '" + VisitID + @"','"
                                      + PatientName + @"',
                                        '" + Age + @"',                               
                                        '" + Bed_No + @"',
                                         '" + InDate + @"',
                                          '" + DepId + @"',
                                          '" + DepName + @"',
                                            '" + LoginUser.DepartmentCode + @"',
                                          '" + LoginUser.DepartmentName + @"',
                                          '" + date + @"',
                                          '" + time + @"',  
                                          '" + WeeHour + @"',
                                         '" + breadfastbefore + @"',
                                          '" + breadfastafter + @"',
                                         '" + lunchbefore + @"',
                                          '" + lunchafter + @"',
                                         '" + dinnerbefore + @"',
                                         '" + dinnerafter + @"',
                                         '" + bedtime + @"',
                                         '" + sugartime1 + @"',
                                         '" + sugar1 + @"',
                                         '" + sugartime2 + @"',
                                         '" + sugar2 + @"',
                                         '" + sugartime3 + @"',
                                         '" + sugar3 + @"',
                                         '" + sugartime4 + @"',
                                         '" + sugar4 + @"',
                                         '" + ketonetime1 + @"',
                                         '" + ketone1 + @"',
                                         '" + ketonetime2 + @"',
                                         '" + ketone2 + @"',                                         
                                         '" + LoginUser.UserId + @"',
                                         '" + LoginUser.UserName + @"',
                                         '" + System.DateTime.Now.ToString() + @"',
                                         '" + syncSN + @"'
                                         )";
            SqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, TempInsert);
        }
        private void UpdateClinicalNursingPrint(string id)
        {
            string PID = this.Patientinfo[0];
            //DataRow CurRow = PName.Select("Name_Bed like '" + PID.Trim() + "%'")[0];
            string VisitID = this.Patientinfo[1];
            string Bed_No = this.Patientinfo[5];
            string InDate = this.Patientinfo[6];
            string PatientName = this.Patientinfo[2];
            string Age = this.Patientinfo[4];

            string selectsql = @"SELECT 
                                   [Id]
                                  ,[PatientId]
                                  ,[VISIT_ID]
                                  ,[PatientName]
                                  ,[DepId]
                                  ,[DepName]
                                  ,[AreaId]
                                  ,[AreaName]
                                  ,[Date]
                                  ,[Time]
                                  ,[data]
                                  ,[SubmituserId]
                                  ,[SubmituserName]
                                  ,[Updatetime]
                                  ,[UpdateuserId]
                                  ,[UpdateuserName]
                                  ,[syncSN]
                              FROM [BNNursingDocsSystem_Develop].[dbo].[t_Bloodsugar](NOLOCK) where Id = '" + id + "'";
            DataTable selectNursingForm = SqlHelper.ExecuteDataset(selectsql, System.Data.CommandType.Text).Tables[0];
            XmlDocument xmlDoc = new XmlDocument();
            StringReader Nurseingdata = new StringReader(selectNursingForm.Rows[0]["data"].ToString());
            xmlDoc.Load(Nurseingdata);
            XmlNode nursingrecord = xmlDoc.SelectSingleNode("/BloodSugarRecordDocument");
            string WeeHour = nursingrecord.ChildNodes[0].InnerText.Trim();
            string breadfastbefore = nursingrecord.ChildNodes[1].InnerText.Trim();
            string breadfastafter = nursingrecord.ChildNodes[2].InnerText.Trim();
            string lunchbefore = nursingrecord.ChildNodes[3].InnerText.Trim();
            string lunchafter = nursingrecord.ChildNodes[4].InnerText.Trim();
            string dinnerbefore = nursingrecord.ChildNodes[5].InnerText.Trim();
            string dinnerafter = nursingrecord.ChildNodes[6].InnerText.Trim();
            string bedtime = nursingrecord.ChildNodes[7].InnerText.Trim();
            string sugar1 = nursingrecord.ChildNodes[8].InnerText.Trim();
            string sugartime1 = nursingrecord.ChildNodes[9].InnerText.Trim();
            string sugar2 = nursingrecord.ChildNodes[10].InnerText.Trim();
            string sugartime2 = nursingrecord.ChildNodes[11].InnerText.Trim();
            string sugar3 = nursingrecord.ChildNodes[12].InnerText.Trim();
            string sugartime3 = nursingrecord.ChildNodes[13].InnerText.Trim();
            string sugar4 = nursingrecord.ChildNodes[14].InnerText;
            string sugartime4 = nursingrecord.ChildNodes[15].InnerText;
            string ketone1 = nursingrecord.ChildNodes[16].InnerText;
            string ketonetime1 = nursingrecord.ChildNodes[17].InnerText;
            string ketone2 = nursingrecord.ChildNodes[18].InnerText;
            string ketonetime2 = nursingrecord.ChildNodes[19].InnerText;

            string date = selectNursingForm.Rows[0]["Date"].ToString();
            string time = selectNursingForm.Rows[0]["Time"].ToString();
            string DepId = selectNursingForm.Rows[0]["DepId"].ToString();
            string DepName = selectNursingForm.Rows[0]["DepName"].ToString();
            string syncSN = selectNursingForm.Rows[0]["syncSN"].ToString();

            string update = @"use BNNursingDocsSystem_Develop ; update t_Bloodsugar_Print set 
Age = '" + Age + "',Bed_No = '" + Bed_No + "',InTime = '" + InDate + "',DepId ='" + DepId + "',DepName ='" + DepName + "',AreaId ='" + LoginUser.DepartmentCode + "',AreaName ='" + LoginUser.DepartmentName + "'," +
                  "[Date] =  '" + date + @"'
                    ,[Time] = '" + time + @"'
                    ,[WeeHour] = '" + WeeHour + @"'
                    ,[breadfastbefore] = '" + breadfastbefore + @"'
                    ,[breadfastafter] = '" + breadfastafter + @"'
                    ,[lunchbefore] = '" + lunchbefore + @"'
                    ,[lunchafter] = '" + lunchafter + @"'
                    ,[dinnerbefore] = '" + dinnerbefore + @"'
                    ,[dinnerafter] = '" + dinnerafter + @"'
                    ,[bedtime] = '" + bedtime + @"'
                    ,[sugar1] = '" + (string.IsNullOrEmpty(sugartime1) ? "" : sugartime1) + @"'
                    ,[sugartime1] = '" + sugar1 + @"'
                    ,[sugar2] = '" + (string.IsNullOrEmpty(sugartime2) ? "" : sugartime2) + @"'
                    ,[sugartime2] = '" + sugar2 + @"'
                    ,[sugar3] = '" + (string.IsNullOrEmpty(sugartime3) ? "" : sugartime3) + @"'
                    ,[sugartime3] = '" + sugar3 + @"'
                    ,[sugar4] = '" + (string.IsNullOrEmpty(sugartime4) ? "" : sugartime4) + @"'
                    ,[sugartime4] = '" + sugar4 + @"'
                    ,[ketone1] = '" + (string.IsNullOrEmpty(ketonetime1) ? "" : ketonetime1) + @"'
                    ,[ketonetime1] = '" + ketone1 + @"'
                    ,[ketone2] = '" + (string.IsNullOrEmpty(ketonetime2) ? "" : ketonetime2) + @"'
                    ,[ketonetime2] = '" + ketone2 + @"'
                    ,[SubmituserId] = '" + LoginUser.UserId + @"'
                    ,[SubmituserName] = '" + LoginUser.UserName + @"'    
                    ,[PrintTime] = '" + System.DateTime.Now.ToString() + @"'    
                    ,[syncSN] = '" + syncSN + @"'    
                  WHERE BloodsugarId='" + id + "'";
            SqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, update);
        }


        #endregion

        #region 删除事件
        /// <summary>
        /// 删除护理记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Del_Click(object sender, EventArgs e)
        {
            int num = bandedGridView1.GetSelectedRows().Length;
            if (num == 0)
            {
                if (bandedGridView1.RowCount > 0) { XtraMessageBox.Show("请选择要删除血糖记录的患者"); }
                return;
            }

            DialogResult Delete;
            Delete = XtraMessageBox.Show("确定要删除吗？", "删除询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (Delete == DialogResult.OK)
            {
                num = bandedGridView1.GetSelectedRows()[0];
                string id = bandedGridView1.GetRowCellValue(num, "ID").ToString();
                string delete = @"use BNNursingDocsSystem_Develop ; update t_Bloodsugar set 
                  [PatientId] =  [PatientId] +'删除'
                 ,[Updatetime] = '" + System.DateTime.Now.ToString() + @"'
                ,[UpdateuserId] = '" + LoginUser.UserId + @"'
                ,[UpdateuserName] = '" + LoginUser.UserName + @"'            
                  WHERE Id='" + id + "'";
                int key = SqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, delete);
                if (key > 0)
                {
                    XtraMessageBox.Show("删除成功");
                    #region 上传海泰
                    if (Base.ESSwitchHT == "1")
                    {

                        SynchroBLL synchro = new SynchroBLL();
                        ClinicalNursinguser cn = new ClinicalNursinguser();
                        cn.PatientId = bandedGridView1.GetRowCellValue(num, "PatientId").ToString();
                        cn.PatientName = bandedGridView1.GetRowCellValue(num, "PatientName").ToString();
                        cn.data = bandedGridView1.GetRowCellValue(num, "data").ToString();
                        cn.Updatetime = System.DateTime.Now;
                        cn.UpdateuserId = LoginUser.UserId;
                        cn.UpdateuserName = LoginUser.UserName;
                        string syncSN_Sql = string.Format("SELECT syncSN FROM dbo.t_Bloodsugar(NOLOCK) WHERE id = {0}", id);
                        string syncSN = SqlHelper.ExecuteDataset(syncSN_Sql, CommandType.Text).Tables[0].Rows[0][0] + "";
                        cn.syncSN = syncSN;
                        synchro.bloodsugarInfoAsyncToEMRDelegateMethod(cn, "3");
                    }
                    #endregion
                    cbb_PatientSel_SelectedIndexChanged(null, null);
                }
                else
                {
                    XtraMessageBox.Show("删除失败");
                }
            }
        }
        #endregion

        #region 加载数据
        /// <summary>
        /// 加载患者记录单数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbb_PatientSel_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.Patientinfo[0] == null) return;
            string PID = this.Patientinfo[0];
            string VisitID = this.Patientinfo[1];

            if (!string.IsNullOrEmpty(PID))
            {
                //构造sql查询
                string selectsql = @" SELECT [ID],[PatientId],[VISIT_ID],[PatientName],[DepId],[DepName],[AreaId],[AreaName] ,[Date],[Time],[data],[Submittime],[SubmituserId],[SubmituserName],[Updatetime] ,[UpdateuserId],[UpdateuserName],[syncSN],' 'as Morning3 ,' 'as Breakfast1  ,' 'as Breakfast2  ,' 'as Lunch1  ,' 'as Lunch2  ,' 'as Dinner1  ,' 'as Dinner2  ,' 'as BeforeSleep  ,' 'as OtherTime1  ,' 'as OtherMol1 ,' 'as OtherTime2 ,' 'as OtherMol2 ,' 'as OtherTime3 ,' 'as OtherMol3 ,' 'as OtherTime4 ,' 'as OtherMol4 ,' 'as BloodKetoneTime ,' 'as BloodKetoneAmount ,' 'as BloodKetoneTime2 ,' 'as BloodKetoneAmount2 FROM [BNNursingDocsSystem_Develop].[dbo].[t_Bloodsugar](NOLOCK) WHERE PatientId ='{0}' AND VISIT_ID ='{1}' AND CONVERT(DATETIME,CASE WHEN ISDATE([Date])=0 THEN '2000-01-01' ELSE [Date] END
 ) BETWEEN CONVERT(DATETIME,'{2}') AND CONVERT(DATETIME,'{3}') ORDER BY Date DESC,Time DESC ";
                selectsql = string.Format(selectsql, PID, VisitID, dateE_StartTime.Text, (dateE_EndTime.Text + " 23:59:59"));
                DataSet Ds = SqlHelper.ExecuteDataset(selectsql, System.Data.CommandType.Text);
                if (Ds == null || Ds.Tables.Count <= 0) return;
                DataTable selectNursingForm = new DataTable();
                if (Ds.Tables != null && Ds.Tables.Count > 0)
                {
                    selectNursingForm = Ds.Tables[0];
                    if (selectNursingForm != null && selectNursingForm.Rows.Count > 0)
                    {
                        gridControl1.DataSource = selectNursingForm;
                        for (int i = 0; i < selectNursingForm.Rows.Count; i++)
                        {
                            XmlDocument xmlDoc = new XmlDocument();
                            StringReader Nurseingdata = new StringReader(selectNursingForm.Rows[i]["data"].ToString());
                            xmlDoc.Load(Nurseingdata);
                            XmlNode nursingrecord = xmlDoc.SelectSingleNode("/BloodSugarRecordDocument");
                            string Morning3 = nursingrecord.ChildNodes[0].InnerText;
                            string Breakfast1 = nursingrecord.ChildNodes[1].InnerText;
                            string Breakfast2 = nursingrecord.ChildNodes[2].InnerText;
                            string Lunch1 = nursingrecord.ChildNodes[3].InnerText;
                            string Lunch2 = nursingrecord.ChildNodes[4].InnerText;
                            string Dinner1 = nursingrecord.ChildNodes[5].InnerText;
                            string Dinner2 = nursingrecord.ChildNodes[6].InnerText;
                            string BeforeSleep = nursingrecord.ChildNodes[7].InnerText;
                            string OtherTime1 = nursingrecord.ChildNodes[8].InnerText;
                            string OtherMol1 = nursingrecord.ChildNodes[9].InnerText;
                            string OtherTime2 = nursingrecord.ChildNodes[10].InnerText;
                            string OtherMol2 = nursingrecord.ChildNodes[11].InnerText;
                            string OtherTime3 = nursingrecord.ChildNodes[12].InnerText;
                            string OtherMol3 = nursingrecord.ChildNodes[13].InnerText;
                            string OtherTime4 = nursingrecord.ChildNodes[14].InnerText;
                            string OtherMol4 = nursingrecord.ChildNodes[15].InnerText;
                            string BloodKetoneTime = nursingrecord.ChildNodes[16].InnerText;
                            string BloodKetoneAmount = nursingrecord.ChildNodes[17].InnerText;
                            string BloodKetoneTime2 = nursingrecord.ChildNodes[18].InnerText;
                            string BloodKetoneAmount2 = nursingrecord.ChildNodes[19].InnerText;
                            bandedGridView1.SetRowCellValue(i, "Morning3", Morning3);//凌晨3点
                            bandedGridView1.SetRowCellValue(i, "Breakfast1", Breakfast1);//早餐前
                            bandedGridView1.SetRowCellValue(i, "Breakfast2", Breakfast2);//早餐后
                            bandedGridView1.SetRowCellValue(i, "Lunch1", Lunch1);//午餐前
                            bandedGridView1.SetRowCellValue(i, "Lunch2", Lunch2);//午餐后
                            bandedGridView1.SetRowCellValue(i, "Dinner1", Dinner1);//晚餐前
                            bandedGridView1.SetRowCellValue(i, "Dinner2", Dinner2);//晚餐后
                            bandedGridView1.SetRowCellValue(i, "BeforeSleep", BeforeSleep);//睡前
                            bandedGridView1.SetRowCellValue(i, "OtherTime1", DateTimeHelper.HHmmssToHHmm(OtherTime1));//其他时间点：时间
                            bandedGridView1.SetRowCellValue(i, "OtherMol1", OtherMol1);//血糖
                            bandedGridView1.SetRowCellValue(i, "OtherTime2", DateTimeHelper.HHmmssToHHmm(OtherTime2));//时间
                            bandedGridView1.SetRowCellValue(i, "OtherMol2", OtherMol2);//血糖
                            bandedGridView1.SetRowCellValue(i, "OtherTime3", DateTimeHelper.HHmmssToHHmm(OtherTime3));//时间
                            bandedGridView1.SetRowCellValue(i, "OtherMol3", OtherMol3);//血糖
                            bandedGridView1.SetRowCellValue(i, "OtherTime4", DateTimeHelper.HHmmssToHHmm(OtherTime4));//时间
                            bandedGridView1.SetRowCellValue(i, "OtherMol4", OtherMol4);//血糖
                            bandedGridView1.SetRowCellValue(i, "BloodKetoneTime", DateTimeHelper.HHmmssToHHmm(BloodKetoneTime));//时间
                            bandedGridView1.SetRowCellValue(i, "BloodKetoneAmount", BloodKetoneAmount);//血酮
                            bandedGridView1.SetRowCellValue(i, "BloodKetoneTime2", DateTimeHelper.HHmmssToHHmm(BloodKetoneTime2));//时间
                            bandedGridView1.SetRowCellValue(i, "BloodKetoneAmount2", BloodKetoneAmount2);//血酮
                        }
                    }
                    else gridControl1.DataSource = selectNursingForm;
                }
                else gridControl1.DataSource = selectNursingForm;
            }
        }
        #endregion

        #region 修改事件
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            int num = bandedGridView1.GetSelectedRows().Length > 0 ? bandedGridView1.GetSelectedRows()[0] : -1;
            if (num == -1)
            {
                if (bandedGridView1.RowCount > 0) { XtraMessageBox.Show("请选择要修改血糖记录的患者"); }
                return;
            }
            string id = bandedGridView1.GetRowCellValue(num, "ID").ToString();
            string PID = this.Patientinfo[0];
            string VisitID = this.Patientinfo[1];
            string bedno = this.Patientinfo[5];
            string Name = this.Patientinfo[2];
            BloodGlucEntryForm NEF = new BloodGlucEntryForm(this.UserParam, this.Patientinfo, id);
            NEF.ShowDialog();
            cbb_PatientSel_SelectedIndexChanged(null, null);
        }
        #endregion

        #region 日期变化
        private void dateE_StartTime_TextChanged(object sender, EventArgs e)
        {
            cbb_PatientSel_SelectedIndexChanged(null, null);
        }
        #endregion

        #region 趋势图事件和方法
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            if (bandedGridView1.GetSelectedRows().Count() == 0)
            {
                MessageBox.Show("没有数据可以查看！");
                return;
            }
            int num = bandedGridView1.GetSelectedRows()[0];
            string id = bandedGridView1.GetRowCellValue(num, "ID").ToString();
            string PID = this.Patientinfo[0];
            //DataRow CurRow = PName.Select("Name_Bed like '" + PID.Trim() + "%'")[0];
            //PID = CurRow["PATIENT_ID"].ToString().Trim();
            string VisitID = this.Patientinfo[1];
            string Name = this.Patientinfo[2];
            string url = "http://172.29.102.132:7777/NursingInfoSystem/Bloodsugar?patientId=" + PID + "&visitId=" + VisitID + "&patientName=" + Name + "&tdsourcetag=s_pctim_aiomsg";
            OpenDefaultBrowserUrl(url);
        }

        /// <summary>
        /// 打开系统默认浏览器（用户自己设置了默认浏览器）
        /// </summary>
        /// <param name="url"></param>
        public static void OpenDefaultBrowserUrl(string url)
        {
            try
            {
                // 方法1
                //从注册表中读取默认浏览器可执行文件路径
                RegistryKey key = Registry.ClassesRoot.OpenSubKey(@"http\shell\open\command\");
                if (key != null)
                {
                    string s = key.GetValue("").ToString();
                    //s就是你的默认浏览器，不过后面带了参数，把它截去，不过需要注意的是：不同的浏览器后面的参数不一样！
                    //"D:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -- "%1"
                    var lastIndex = s.IndexOf(".exe", StringComparison.Ordinal);
                    if (lastIndex == -1)
                    {
                        lastIndex = s.IndexOf(".EXE", StringComparison.Ordinal);
                    }
                    var path = s.Substring(1, lastIndex + 3);
                    var result = Process.Start(path, url);
                    if (result == null)
                    {
                        // 方法2
                        // 调用系统默认的浏览器 
                        var result1 = Process.Start("explorer.exe", url);
                        if (result1 == null)
                        {
                            // 方法3
                            Process.Start(url);
                        }
                    }
                }
                else
                {
                    // 方法2
                    // 调用系统默认的浏览器 
                    var result1 = Process.Start("explorer.exe", url);
                    if (result1 == null)
                    {
                        // 方法3
                        Process.Start(url);
                    }
                }
            }
            catch
            {
                OpenIe(url);
            }
        }
        /// <summary>
        /// 用IE打开浏览器
        /// </summary>
        /// <param name="url"></param>
        public static void OpenIe(string url)
        {
            try
            {
                Process.Start("iexplore.exe", url);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                // IE浏览器路径安装：C:\Program Files\Internet Explorer
                // at System.Diagnostics.process.StartWithshellExecuteEx(ProcessStartInfo startInfo)注意这个错误
                try
                {
                    if (File.Exists(@"C:\Program Files\Internet Explorer\iexplore.exe"))
                    {
                        ProcessStartInfo processStartInfo = new ProcessStartInfo
                        {
                            FileName = @"C:\Program Files\Internet Explorer\iexplore.exe",
                            Arguments = url,
                            UseShellExecute = false,
                            CreateNoWindow = true
                        };
                        Process.Start(processStartInfo);
                    }
                    else
                    {
                        if (File.Exists(@"C:\Program Files (x86)\Internet Explorer\iexplore.exe"))
                        {
                            ProcessStartInfo processStartInfo = new ProcessStartInfo
                            {
                                FileName = @"C:\Program Files (x86)\Internet Explorer\iexplore.exe",
                                Arguments = url,
                                UseShellExecute = false,
                                CreateNoWindow = true
                            };
                            Process.Start(processStartInfo);
                        }
                        else
                        {
                            if (MessageBox.Show(@"系统未安装IE浏览器，是否下载安装？", null, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                // 打开下载链接，从微软官网下载
                                OpenDefaultBrowserUrl("http://windows.microsoft.com/zh-cn/internet-explorer/download-ie");
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
            }
        }
        #endregion

        #region 双击列表中的项目修改事件
        private void bandedGridView1_DoubleClick(object sender, EventArgs e)
        {
            int num = bandedGridView1.GetSelectedRows().Length > 0 ? bandedGridView1.GetSelectedRows()[0] : -1;
            if (num == -1)
            {
                if (bandedGridView1.RowCount > 0) { XtraMessageBox.Show("请选择要修改血糖记录的患者"); }
                return;
            }
            string id = bandedGridView1.GetRowCellValue(num, "ID").ToString();
            string PID = this.Patientinfo[0];
            //DataRow CurRow = PName.Select("Name_Bed like '" + PID.Trim() + "%'")[0];
            string VisitID = this.Patientinfo[1];
            string bedno = this.Patientinfo[5];
            string Name = this.Patientinfo[2];
            BloodGlucEntryForm NEF = new BloodGlucEntryForm(this.UserParam, this.Patientinfo, id);
            NEF.ShowDialog();
            cbb_PatientSel_SelectedIndexChanged(null, null);
        }
        #endregion

        #region 加载历史病人事件和方法
        //加载历史病人
        private void btnHistory_Click(object sender, EventArgs e)
        {
            BloodHistorySearch b = new BloodHistorySearch(UserParam);
            b.ShowDialog();
            if (b.DialogResult == DialogResult.Yes)
            {
                PID = b.PatientID;
                VID = b.VisitID;

                if (BloodHistorySearch.ReturnPatientEntity.PatientName != null)
                {
                    labelName.Text = ChooseOutPatiens.ReturnPatientEntity.PatientName;
                    labelSex.Text = ChooseOutPatiens.ReturnPatientEntity.Sex;
                    labelPatientID.Text = ChooseOutPatiens.ReturnPatientEntity.PatientID;
                    labelInDate.Text = ChooseOutPatiens.ReturnPatientEntity.InDate;
                    labelBed.Text = ChooseOutPatiens.ReturnPatientEntity.BedNo;
                }
                LoadOldPatients(VID);
            }
        }
        public void LoadOldPatients(string VisitID)
        {
            string selectsql = @"SELECT 
       [ID]
      ,[PatientId]
      ,[VISIT_ID]
      ,[PatientName]
      ,[DepId]
      ,[DepName]
      ,[AreaId]
      ,[AreaName]
      ,[Date]
      ,[Time]
      ,[data]
      ,[Submittime]
      ,[SubmituserId]
      ,[SubmituserName]
      ,[Updatetime]
      ,[UpdateuserId]
      ,[UpdateuserName]
      ,[syncSN]
 ,' 'as Morning3
 ,' 'as Breakfast1 
 ,' 'as Breakfast2 
 ,' 'as Lunch1 
 ,' 'as Lunch2 
 ,' 'as Dinner1 
 ,' 'as Dinner2 
 ,' 'as BeforeSleep 
 ,' 'as OtherTime1 
 ,' 'as OtherMol1
 ,' 'as OtherTime2
 ,' 'as OtherMol2
 ,' 'as OtherTime3
 ,' 'as OtherMol3
 ,' 'as OtherTime4
 ,' 'as OtherMol4
 ,' 'as BloodKetoneTime
 ,' 'as BloodKetoneAmount
 ,' 'as BloodKetoneTime2
 ,' 'as BloodKetoneAmount2
  FROM [BNNursingDocsSystem_Develop].[dbo].[t_Bloodsugar](NOLOCK) where PatientId ='" + PID + "' and VISIT_ID ='" + VisitID + "' and Date between '" + dateE_StartTime.Text + "' and '" + dateE_EndTime.Text + "'order by Date,Time";
            DataSet dsResult = SqlHelper.ExecuteDataset(selectsql, CommandType.Text);
            if (dsResult == null || dsResult.Tables.Count == 0)
            {
                return;
            }
            //DataTable selectNursingForm = SqlHelper.ExecuteDataset(selectsql, CommandType.Text).Tables[0];
            DataTable selectNursingForm = dsResult.Tables[0];
            if (selectNursingForm.Rows.Count > 0)
            {
                gridControl1.DataSource = selectNursingForm;
                for (int i = 0; i < selectNursingForm.Rows.Count; i++)
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    StringReader Nurseingdata = new StringReader(selectNursingForm.Rows[i]["data"].ToString());
                    xmlDoc.Load(Nurseingdata);
                    XmlNode nursingrecord = xmlDoc.SelectSingleNode("/BloodSugarRecordDocument");
                    string Morning3 = nursingrecord.ChildNodes[0].InnerText;
                    string Breakfast1 = nursingrecord.ChildNodes[1].InnerText;
                    string Breakfast2 = nursingrecord.ChildNodes[2].InnerText;
                    string Lunch1 = nursingrecord.ChildNodes[3].InnerText;
                    string Lunch2 = nursingrecord.ChildNodes[4].InnerText;
                    string Dinner1 = nursingrecord.ChildNodes[5].InnerText;
                    string Dinner2 = nursingrecord.ChildNodes[6].InnerText;
                    string BeforeSleep = nursingrecord.ChildNodes[7].InnerText;
                    string OtherTime1 = nursingrecord.ChildNodes[8].InnerText;
                    string OtherMol1 = nursingrecord.ChildNodes[9].InnerText;
                    string OtherTime2 = nursingrecord.ChildNodes[10].InnerText;
                    string OtherMol2 = nursingrecord.ChildNodes[11].InnerText;
                    string OtherTime3 = nursingrecord.ChildNodes[12].InnerText;
                    string OtherMol3 = nursingrecord.ChildNodes[13].InnerText;
                    string OtherTime4 = nursingrecord.ChildNodes[14].InnerText;
                    string OtherMol4 = nursingrecord.ChildNodes[15].InnerText;
                    string BloodKetoneTime = nursingrecord.ChildNodes[16].InnerText;
                    string BloodKetoneAmount = nursingrecord.ChildNodes[17].InnerText;
                    string BloodKetoneTime2 = nursingrecord.ChildNodes[18].InnerText;
                    string BloodKetoneAmount2 = nursingrecord.ChildNodes[19].InnerText;
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[1], Morning3);//凌晨3点
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[2], Breakfast1);//早餐前
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[3], Breakfast2);//早餐后
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[5], Lunch1);//午餐前
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[6], Lunch2);//午餐后
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[14], Dinner1);//晚餐前
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[7], Dinner2);//晚餐后
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[8], BeforeSleep);//睡前
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[9], OtherTime1);//其他时间点：时间
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[10], OtherMol1);//血糖
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[11], OtherTime2);//时间
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[19], OtherMol2);//血糖
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[16], OtherTime3);//时间
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[17], OtherMol3);//血糖
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[18], OtherTime4);//时间
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[15], OtherMol4);//血糖
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[12], BloodKetoneTime);//时间
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[13], BloodKetoneAmount);//血酮
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[20], BloodKetoneTime2);//时间
                    bandedGridView1.SetRowCellValue(i, bandedGridView1.Columns[21], BloodKetoneAmount2);//血酮
                }

            }
            else gridControl1.DataSource = selectNursingForm;
        }
        #endregion
    }
}
